package com.dcache.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

/**
 * Created by Administrator on 17/4/21.
 */
public class Utils {

    private static final Gson gson1 = new GsonBuilder().disableHtmlEscaping().setDateFormat("yyyy/MM/dd HH:mm:ss")
            .create();
    private static final Gson gson2 = new GsonBuilder().disableHtmlEscaping().setDateFormat("yyyy/MM/dd HH:mm:ss")
            .setPrettyPrinting().create();

    private static JsonParser jsonParser = new JsonParser();

    public  static HttpEntity jsonHttpEntity(Object params) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        return new HttpEntity<String>(Utils.toJson(params), headers);
    }

    public static String toJson(Object object) {

        try {
            return gson1.toJson(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String toPrettyJson(String json) {

        try {
            JsonElement jsonElement = jsonParser.parse(json);

            return gson2.toJson(jsonElement);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static <T> T json2Object(String json, Class<T> classOfT) {

        try {
            return gson1.fromJson(json, classOfT);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
